import { useTranslation } from "react-i18next";
import { Image, Input, Toast } from "antd-mobile";
import { useCallback, useEffect, useState } from "react";
import HeaderComponent from "@/components/HeaderComponent/HeaderComponent";

import getAssetsFile from "@/utils/pub-use";
import { useAppSelector } from "@/hooks/useAppSelector";
import {
  getApiToken,
  getCurrencyList,
  swap,
  swapEnum,
  hangForSale,
} from "@/api/module/U2U";
import { debounce } from "lodash";
import { CenterPopupComponent } from "@/components/CenterPopupComponent/CenterPopupComponent";
import { FileOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";
import { BanlanceType } from "@/api/module/user";

const AssetsComponent = () => {
  const { t } = useTranslation();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const assetsList = [
    {
      image: getAssetsFile("home/third.png"),
      title: "USDT",
      key: "USDT",
    },
    {
      image: getAssetsFile("home/sixth.png"),
      title: "RegisterBeans",
      key: "ZCB",
    },
    {
      image: getAssetsFile("home/fourth.png"),
      title: "CashBeans",
      key: "XJB",
    },
  ];
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-5 px-4 rounded-xl pb-6 mt-4">
        <div className="left">
          <div className="opacity-50 text-xs">{t("bugRate")}</div>
          <div className="font-bold text-2xl mt-1">$1</div>
        </div>
        <div className="relative right flex items-center">
          <Image
            className="absolute left-0 bg-font-2 p-2 rounded-full"
            src={getAssetsFile("u2u/person-icon.png")}
            width={32}
            height={32}
            alt=""
          />
          <span className="bg-white-7 pl-10 pr-4 rounded-full text-font-2 font-semibold">
            {userInfo.level_name}
          </span>
        </div>
      </div>
      <div className="value text-white-1 py-5 px-4 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-between">
        {assetsList.map((item) => {
          return (
            <div>
              <Image src={item.image} width={32} height={32} alt="" />
              <div className="text-xs opacity-50 mt-2">{t(item.title)}</div>
              <div className="font-bold text-xl mt-1">
                {
                  (userInfo[item.key as keyof typeof userInfo] as BanlanceType)
                    .balance
                }
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const FormComponent = () => {
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const navigate = useNavigate();

  const { t } = useTranslation();
  const [cash, setCash] = useState("");
  const [usdt, setUsdt] = useState("");
  const [receivable, setReceivable] = useState("");
  const [password, setPassword] = useState("");
  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const reqSwap = async () => {
    try {
      console.log("asdasd");
      setVisible(false);
      Toast.show({
        icon: "loading",
      });
      const res = await hangForSale(cash, password, APIToken);
      Toast.clear();
      setAPIToken("");
      Toast.show({ content: res.msg });
      if (res.code == 0) {
        setPassword("");
        setVisible(false);
        setTimeout(() => {
          navigate(-1);
        }, 1000);
      }
      if (res.code == 1 && userInfo.paypwd_status == 0) {
        navigate("/updatePassword");
      }
    } catch (error) {
      Toast.clear();
      setAPIToken("");
    }
  };
  const calculate = useCallback(
    debounce(async function (val) {
      try {
        if (!val) {
          setUsdt("");
          return;
        }
        Toast.show({
          icon: "loading",
        });
        const res = await swap({
          action: swapEnum.calculate,
          currency_cost: "XJB",
          currency_buy: "USDT",
          currency_main: "XJB",
          amount: val,
        });
        Toast.clear();

        if (res.code == 0) {
          if (!res.data.balance_status) {
            Toast.show({
              content: t("balanceInsufficient"),
            });
          } else {
            if (res.data.calculate.error_code == 0) {
              setUsdt(res.data.calculate.receive_amount + "");
              setReceivable(res.data.calculate.slippage_fee + "");
            } else {
              Toast.show({
                content: t("QuantityIncorrect"),
              });
              setUsdt("");
            }
          }
        } else {
          Toast.show({
            content: res.msg,
          });
          setUsdt("");
        }
      } catch (error) {
        setUsdt("");
        Toast.clear();
      }
    }, 300),
    []
  );
  const reqApiToken = async () => {
    try {
      if (!cash || !password) {
        Toast.show({
          content: t("enterCompleteInformation"),
        });
        return;
      }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }

      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };

  const [currencyList, setCurrencyList] = useState<
    Awaited<ReturnType<typeof getCurrencyList>>["data"]
  >({
    list_sale: [],
    list_buy: [],
  });
  const reqCurrencyList = async () => {
    try {
      const res = await getCurrencyList("xjb");
      console.log(res);
      res.code == 0 && setCurrencyList(res.data);
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    reqCurrencyList();
  }, []);
  return (
    <div
      style={{
        fontSize: "95%",
      }}
    >
      <div className="cash">
        <div>{t("CashBeans")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={cash}
          onChange={(val) => {
            setCash(val);
            calculate(val);
          }}
        />
        <div className="text-right mt-2 opacity-50">
          <span>
            {t("minimum")}: {currencyList.list_sale[0]?.min_buy}
          </span>
          <span className="ml-4">
            {t("highest")}: {currencyList.list_sale[0]?.max_buy}
          </span>
        </div>
      </div>
      <div className="USDT mt-4">
        <div>{t("USDT")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          readOnly
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={usdt}
          onChange={(val) => {
            setUsdt(val);
          }}
        />
        <div className="text-right mt-2 opacity-50">
          <span>
            {t("transactionCost")}: {currencyList.list_sale[0]?.slippage_out}
          </span>
        </div>
      </div>
      <div className="receivable mt-4">
        <div>{t("receivable")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          readOnly
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={receivable}
          onChange={(val) => {
            setReceivable(val);
          }}
        />
      </div>
      <div className="password mt-4">
        <div>{t("password")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          type="password"
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={password}
          onChange={(val) => {
            setPassword(val);
          }}
        />
      </div>
      <div
        onClick={() => reqApiToken()}
        className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
      >
        {t("sell")}
      </div>
      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title={`${t("sell")}XJB`}
        content={
          <div>
            <div>
              {t("consume")}: {cash}
              {t("XJB")}
            </div>
            <div>
              {t("obtain")}: {usdt}USDT
            </div>
          </div>
        }
        onClick={() => reqSwap()}
      />
    </div>
  );
};
export default function Buy() {
  const navigate = useNavigate();
  // i18n.changeLanguage('en');
  // const { t, i18n } = useTranslation();
  // const changeI18n = () => {
  //   i18n.changeLanguage(i18n.language == 'en' ? 'zh' : 'en');
  // };
  return (
    <div className="text-white-1 px-3 pb-28">
      <HeaderComponent
        title="sell"
        right={
          <div className="flex justify-end items-center h-full">
            <FileOutline
              onClick={() => navigate("/U2URecord/sell")}
              color="#E99434"
              fontSize={18}
            />
          </div>
        }
      />
      <AssetsComponent />
      <FormComponent />
      {/* <span>{t('U2U')}</span>
      <button onClick={() => changeI18n()}>asd</button> */}
    </div>
  );
}
